//
//  WelcomeViewController.swift
//  Sinaweibo
//
//  Created by 谌桃 on 15/11/30.
//  Copyright © 2015年 ryan.chen. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD

class WelcomeViewController: UIViewController {
    
    override func loadView() {
        
        //重置控制器view的根视图
        view = backImageView
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        //开始动画
        startAnimation()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //这里一定要注意 执行顺序, 如果先图片下载, 然后setupInfo(), 就会出现界面已经完成显示, 甚至跳转了, 但是图片还没在下载, , 然后就会造成图片没有下载成功, 界面已经显示了
        
        //这里图片下载属于异步请求, 所以一定要先执行setupInfo()
        
        setupInfo()
        
        //异步图片下载
        iconImage.sd_setImageWithURL(UserAccountViewModel().userHeadURL, placeholderImage: iconImage.image)

     
    }

    //MARK: 懒加载子控件
    
    //背景图片
    private lazy var backImageView:UIImageView = UIImageView(image: UIImage(named: "ad_background"))
    
    //用户头像
    private lazy var iconImage:UIImageView = UIImageView(image: UIImage(named: "avatar_default_big"))
    
    //文字描述
    private lazy var welcomeText:UILabel = {
        
        let label = UILabel()
        
        if let account:UserAccount = UserAccountViewModel().account {
            
             label.text = "欢迎归来" + "\(UserAccountViewModel().account!.name!)"
        }
        
        return label
        }()
   
    
    //MARK:添加子控件, 进行布局
    private func setupInfo(){
    
        view.addSubview(iconImage)
        view.addSubview(welcomeText)
        
        iconImage.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(view.snp_centerX)
            make.bottom.equalTo(view.snp_bottom).offset(-180)
            make.size.equalTo(CGSize(width: 90, height: 90))
        }
       
        welcomeText.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(iconImage.snp_centerX)
            make.top.equalTo(iconImage.snp_bottom).offset(18)
        }
        
        //设置圆角
        iconImage.layer.cornerRadius = 45
        iconImage.clipsToBounds = true
    }
    
    //让头像以动画的形式从下往上移动
    private func startAnimation(){
    
        //对于已经添加过的约束 属性 需要修改  可以使用snp_updateConstraints
        iconImage.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(self.view.snp_bottom).offset(-height + 180)
        }
        
        //以动画的形式 强制提前刷新页面
        UIView.animateWithDuration(2.0, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 9.8, options: [], animations: { () -> Void in
            
            //强制提前刷新页面
            self.view.layoutIfNeeded()
            
            }) { (_) -> Void in
                
                //动画完成结束后 , 发送通知 , 切换控制器 到  主控制器 ,object: nil 为nil就相当于广播, 所以监听着都能收到
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVCNotification , object: nil)
        }
    }
}
